<template>
  <div class="home">
    <form action="/">
      <van-search
        v-model="searchVal"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
      />
    </form>
    <section>
      <h4>搜索历史</h4>
      <van-button type="danger" icon="delete-o"  size="small" @click="clear">清空历史记录</van-button>
    </section>
    
    <p>
      <van-button type="info" size="small" v-for="(item,index) in btnList" :key="index"  @click="jump(item)">{{item}} <van-icon name="cross" /></van-button>
     
    </p>
    <ul>
      <li v-for="(item, index) in downList" :key="index" @click="jump(item)">{{ item }}</li>
    </ul>
    <!-- <img alt="Vue logo" src="../assets/logo.png"> -->
  </div>
</template>

<script>
// @ is an alias to /src
import { Toast } from "vant";
export default {
  name: "Home",
  components: {},
  data() {
    return {
      searchVal: "",
      list: [
        "奥迪A1",
        "奥迪A2",
        "奥迪A3",
        "奥迪A6",
        "宝马",
        "宝马730",
        "宝骏",
        "奔驰",
        "比亚迪",
      ],
      btnList:[], // 搜索历史的按钮组
    };
  },
  created(){
    this.btnList = JSON.parse(localStorage.getItem('btnList')) || [];
  },
  computed: {
    downList() {
      //存放搜索出来的内容
      let arr = [];
      if (this.searchVal) {
        arr = this.list.filter((item) => item.includes(this.searchVal));
      }
      //  console.log(arr);
      return arr;
    },
  },
  methods: {
    onSearch() {
      // includes 判断数组或者字符串中是否包含某一项，包含返回true 不包含返回false
      // let str =  '宝马730';
      //  console.log(str.c('6'));

      // 确定搜索的事件
      this.jump(this.searchVal);
      // console.log(this.searchVal);
    },
    onCancel() {
      // 取消搜索的事件
      Toast("取消");
    },
    jump(val){
      this.$router.push({path:'/about',query:{value:val}})
      let bool = this.btnList.some(item => item == val);
      if (!bool){
        this.btnList.push(val);
        localStorage.setItem('btnList',JSON.stringify(this.btnList));
      }
    },
    clear(){ // 清空历史记录的函数
      localStorage.removeItem('btnList');
      this.btnList = [];
    }
  },
};
</script>
<style lang="scss" scoped>
.home {
  position: relative;
}
section{
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
  align-items: center;
}
p{
  display: flex;
  padding: 0 10px;
  flex-wrap: wrap;
  .van-button--small{
    margin-left: 10px;
  }
}
ul {
  position: absolute;
  top: 54px;
  left: 0;
  width: 100%;
  background: #fff;
  z-index: 99;
  li {
    width: 100%;
    line-height: 40px;
    padding: 0 10px;
    border-bottom: 1px solid #ccc;
    text-align: left;
  }
}
</style>
